package physgin;

import java.util.List;

/**
 * Controls the movement of Body objects, 
 * by the calling of appropriate methods regularly.
 * Performs collision checking, by calling the required methods.
 * Tells Body objects to update themselves regularly.
 */
class Collisions implements Runnable
    {
        private BodyController b;
        
        /**
         * Default class constructor.
         * Requires a reference to the BodyController
         * to use to obtain Body objects to check collisions of.
         *
         * @param   b   BodyController
         * @see         BodyController
         */
        Collisions(BodyController b)
        {
            this.b = b;
        }
        
        /**
         * Starts the thread running, and so sets all the objects in the
         * world in motion.  
         *
         * @return      void
         */
        public void run()
        {
            while(true)
            {
                try {
                    Thread.sleep(20);
                }
                catch (InterruptedException e) { }
                detect();
            }
        } 
        
        private void detect()
        {
            List<Body> bodies = b.getBodies();
            for(int i = 0; i < bodies.size(); i++)
            {
                bodies.get(i).updatePos();
                for(int j = 0; j < bodies.size(); j++)
                {
                    if(i != j) 
                    {
                        if(bodies.get(i).equals(bodies.get(j)))
                        {
                            resolve(bodies.get(i), bodies.get(j));
                        }
                    }
                }
                bodies.get(i).update();
            }    
        }
        
        private void resolve(Body a, Body b)
        {
            Physics pA = a.getPhys();
            Physics pB = b.getPhys();
            
            a.resolve(pB);
            b.resolve(pA);
        }
    }
